//
//  BaseVC.m
//  HousingPoliceAssistant
//
//  Created by 云警01 on 2019/6/6.
//  Copyright © 2019 盛洋. All rights reserved.
//

#import "BaseVC.h"
#import "NoDataBtnView.h"
#import "IQKeyboardManager.h"

#import "LoginVC.h"
#import "HomeVC.h"


@interface BaseVC ()<TryAgainViewDelegate,NoDataBtnViewDelegate>
{
    BOOL is_loading;
}

@property (strong, nonatomic) MBProgressHUD *HUD;
@property(strong,nonatomic) TryAgainView *errorView;
@property(strong,nonatomic) NoDataView *NoResult;
@property(strong,nonatomic) NoDataBtnView *NoDataBtnView;

@property(nonatomic, copy) void (^LeftButtonClick)(void);
@property(nonatomic, copy) void (^RightButtonClick)(void);
@end

@implementation BaseVC
@synthesize titleView;
- (BOOL)prefersHomeIndicatorAutoHidden{
    
    return YES;
    
}

- (void)viewDidLoad{
    [super viewDidLoad];
    self.view.frame = CGRectMake(0, 0, SCREEN_W, SCREEN_H);
    titleView = [[NavTitleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, StatusBarAndNavHeight)];
    [titleView.backBtn addTarget:self action:@selector(back:) forControlEvents:UIControlEventTouchUpInside];
    [self addObserver:self forKeyPath:@"title" options:0 context:NULL];
    [self.view addSubview:titleView];
    
    //背景图
    self.backImgView = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_W, SCREEN_H)];
    self.backImgView.image = [UIImage imageNamed:@"back_view"];
    self.backImgView.contentMode = UIViewContentModeScaleToFill;
    [self.view insertSubview:self.backImgView atIndex:0];
        
    //背景边框(创建view时大小位置以此为基准，防止view超出背景框)
    self.backKuang = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back_center"]];
    self.backKuang.contentMode = UIViewContentModeScaleToFill;
    [self.view insertSubview:self.backKuang atIndex:1];
    [self.backKuang mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(self.view).multipliedBy(0.9);
        make.height.equalTo(self.view).multipliedBy(0.75);
        make.right.equalTo(self.view.mas_right);
        make.centerY.equalTo(self.view.mas_centerY).offset(20);
    }];
    
    if (@available(iOS 11.0, *)) {
        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    NSLog(@"***********当前界面是baseVC基类的%@ 出现***********",[NSString stringWithUTF8String:class_getName([self class])]);
    [self setupUI];
    
    if (self.titleView.titleLabel.text.length > NavTitleMaxLength) {
        self.titleView.titleLabel.text = [NSString stringWithFormat:@"%@...",[self.titleView.titleLabel.text substringToIndex:NavTitleMaxLength]];
    }
}

-(void)showBackCenterKuang:(UIImage *)img{
    //背景中心框
    self.backCenterKuang = [[UIImageView alloc]initWithImage:img];
    self.backCenterKuang.contentMode = UIViewContentModeScaleToFill;
    self.backCenterKuang.bounds = CGRectMake(0, 0, SCREEN_W * 0.9, SCREEN_H * 0.75);
    self.backCenterKuang.center = CGPointMake(CGRectGetWidth(self.view.frame)/2, CGRectGetHeight(self.view.frame)/2 + 20);
    [self.view insertSubview:self.backCenterKuang atIndex:1];
}

- (void)setupUI{

}


/**
 * 添加导航右按钮
 */
- (void)createNavigationBarRightBarButtonItemWithTitle:(NSString *)title font:(CGFloat)font image:(NSString *)image target:(id)target action:(SEL)action
{
    CGFloat width = 50;
    rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(SCREEN_W - width - 15, 0, width, StatusBarAndNavHeight);
    [rightBtn setTitle:title forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [rightBtn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
    rightBtn.titleLabel.font = AutoLabFont3;
    [rightBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    rightBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.titleView addSubview:rightBtn];
}

- (void)SetRightButtonTitle:(NSString *)title image:(NSString *)image
{
    [rightBtn setTitle:title forState:UIControlStateNormal];
    [rightBtn setImage:[UIImage imageNamed:image] forState:UIControlStateNormal];
}

//弹出登陆界面
- (void)goLogin:(UIViewController *)ViewController backType:(int)backType animated:(BOOL)animated{
    
    //获取目前正在展示的vc
    BaseVC *show_vc = (BaseVC *)[[DataService sharedService] currentViewController];
    if (![show_vc isKindOfClass:[LoginVC class]]) {
        //获取当前显示的视图是否已经在登录页面
        LoginVC *userCenterViewController=[[LoginVC alloc] initWithNibName:@"LoginVC" bundle:nil backType:backType];
        BaseNavVC *lognav=[[BaseNavVC alloc] initWithRootViewController:userCenterViewController];
        [ViewController presentViewController:lognav animated:animated completion:nil];
    }
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    [[IQKeyboardManager sharedManager] setEnable:YES];
    //关闭toolbar IQKeyboardManager 会自动为键盘添加一个工具栏，它包含一个左箭头一个右箭头切换输入框，还有一个done按钮来关闭键盘。 可以通过属性 enableAutoToolbar 开启/关闭
    [IQKeyboardManager sharedManager].enableAutoToolbar = YES;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    titleView.titleLabel.text = self.title;
}

- (void)back:(id)sender {
    if (_backClicked != nil) {
        _backClicked();
    } else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

//Push到下一界面
- (void)PushToViewController:(UIViewController*)VC{
    
    [VC setHidesBottomBarWhenPushed:YES];       //加上这句就可以把推出的ViewController隐藏Tabbar
    [self.navigationController pushViewController:VC animated:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //区别于是否为自定义导航栏,如果非自定义 就显示系统导航栏
//    if (![self isKindOfClass:[ShowNavBaseVC class]]) {
    
        /*
         * 基类隐藏系统导航栏
         */
        [self.navigationController setNavigationBarHidden:YES animated:animated];
//    }
    
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:animated];
    
    if (@available(iOS 11.0, *)) {
        [self prefersHomeIndicatorAutoHidden];
    } else {}

    if ([self.navigationController.viewControllers count] <= 1) {
        titleView.backBtn.hidden = YES;
    }else {
        titleView.backBtn.hidden = NO;
    }
}

-(BOOL)isLoadingNow{
    
    return is_loading;
}
//加载动画
-(void)ShowLoading{
    
    is_loading = YES;
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.cornerRadius = 15;
    self.HUD.opacity = .7;
    self.HUD.labelText = @"正在加载...";
}

-(void)ShowLoading:(NSString *)showText{
    
    is_loading = YES;
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.cornerRadius = 15;
    self.HUD.opacity = .7;
    self.HUD.labelText = showText;
}

-(void)HideLoading{
    
    is_loading = NO;
    
    if (self.HUD!=nil) {
        self.HUD.delegate = nil;
        [self.HUD removeFromSuperview];
        self.HUD = nil;
    }
    
}

-(void)ShowNewMsg:(NSString*)str
{
    if ([str isStringContainEnglish]) {
        //不显示英文报错
        return;
    }
    cnhbMsgAlert *alert = [[cnhbMsgAlert alloc] init];
    [alert setTextColor:[UIColor whiteColor]];
    [alert showMessage:str];
}

//-(void)LGShowSuccessMsg:(NSString*)str time:(int)time{
//    [SVProgressHUD showSuccessWithStatus:str duration:time];
//}
//
//-(void)LGShowErrorMsg:(NSString*)str time:(int)time{
//    [SVProgressHUD showErrorWithStatus:str duration:time];
//}

-(void)ShowV3Msg:(NSString *)str
{
    LG_alertview=[[UIAlertView alloc] initWithTitle:@"提示信息" message:str delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    LG_alertview.tag = 666666;
    [LG_alertview show];
}

-(void)ShowV3Msg:(NSString*)str leftBtnTitle:(NSString *)leftTitle rightBtnTitle:(NSString *)rightTitle leftBtnClick:(void(^)(void))LeftBtnClickBlock rightBtnClick:(void(^)(void))RightBtnClickBlock
{
    if (LeftBtnClickBlock) {
        self.LeftButtonClick = ^{
            LeftBtnClickBlock();
        };
    }
    if (RightBtnClickBlock) {
        self.RightButtonClick = ^{
            RightBtnClickBlock();
        };
    }
    UIAlertView *clickAlert=[[UIAlertView alloc] initWithTitle:@"提示信息" message:str delegate:self cancelButtonTitle:leftTitle otherButtonTitles:rightTitle, nil];
    clickAlert.tag = 888;
    clickAlert.delegate = self;
    [clickAlert show];
}

-(void)ShowNoDataBtnView:(UIView *)view Orgin:(CGFloat)Y Title:(NSString *)Title BtnTitle:(NSString *)BtnTitle
{
    if (_NoDataBtnView == nil) {
        _NoDataBtnView  = [[[NSBundle mainBundle] loadNibNamed:@"NoDataBtnView" owner:self options:nil]lastObject];
        _NoDataBtnView.frame = CGRectMake(0, Y, view.frame.size.width, view.frame.size.height-Y);
        _NoDataBtnView.backgroundColor = [UIColor whiteColor];
        if ([Title CheckNSStringData]) {
            _NoDataBtnView.tipLabel.text = Title;
        }
        if ([BtnTitle CheckNSStringData]) {
            _NoDataBtnView.workLabel.text = BtnTitle;
        }
        _NoDataBtnView.delegate = self;
    }
    [view addSubview:_NoDataBtnView];
}

/*
 * 设置工种占位图专用
 */
-(void)ShowNoDataBtnView1:(UIView *)view Orgin:(CGFloat)Y Title:(NSString *)Title BtnTitle:(NSString *)BtnTitle{
    if (_NoDataBtnView == nil) {
        _NoDataBtnView  = [[[NSBundle mainBundle] loadNibNamed:@"NoDataBtnView" owner:self options:nil]lastObject];
        _NoDataBtnView.frame = CGRectMake(0, Y, view.frame.size.width, view.frame.size.height-Y);
        _NoDataBtnView.backgroundColor = [UIColor whiteColor];
        _NoDataBtnView.back_img.image = [UIImage imageNamed:@"shezhi"];
        _NoDataBtnView.workLabel.backgroundColor = [UIColor whiteColor];
        _NoDataBtnView.distance_height.constant = 0;
        _NoDataBtnView.line_view.backgroundColor = [UIColor colorWithHexString:@"4A90E2"];
        _NoDataBtnView.workLabel.textColor = [UIColor colorWithHexString:@"4A90E2"];
        if ([Title CheckNSStringData]) {
            _NoDataBtnView.tipLabel.text = Title;
        }
        if ([BtnTitle CheckNSStringData]) {
            _NoDataBtnView.workLabel.text = BtnTitle;
        }
        _NoDataBtnView.delegate = self;
    }
    [view addSubview:_NoDataBtnView];
}

-(void)HideNoDataBtnView
{
    if (_NoDataBtnView) {
        [_NoDataBtnView removeFromSuperview];
        _NoDataBtnView=nil;
    }
}

-(void)BtnClicked
{
    
}

-(void)ShowNoDataView:(UIView *)view Orgin:(CGFloat)Y
{
    if (!_NoResult) {
        NSArray *array=[[NSBundle mainBundle] loadNibNamed:@"NoDataView" owner:self options:nil];
        self.NoResult=[array objectAtIndex:0];
        self.NoResult.frame = CGRectMake(0, Y, view.frame.size.width, view.frame.size.height-Y);
        if ([_NodataStr CheckNSStringData]) {
            self.NoResult.tipLabel.text = _NodataStr;
        }
        if ([_icon_img CheckNSStringData]) {
            self.NoResult.icon_img.image = [UIImage imageNamed:_icon_img];
        }
        if ([_icon_width CheckNSStringData]) {
            self.NoResult.iconWidth.constant = [_icon_width integerValue];
        }
        if ([_icon_height CheckNSStringData]) {
            self.NoResult.iconWidth.constant = [_icon_height integerValue];
        }
        [view addSubview:_NoResult];
    }
}
-(void)HideNoDataView
{
    if (_NoResult) {
        [_NoResult removeFromSuperview];
        self.NoResult=nil;
    }
}
-(void)ShowerrorView:(UIView *)view Orgin:(CGFloat)Y
{
    if (_errorView == nil) {
        _errorView  = [[[NSBundle mainBundle] loadNibNamed:xibNameTryAgain owner:self options:nil]lastObject];
        _errorView.frame = CGRectMake(0, Y, view.frame.size.width, view.frame.size.height-Y);
        _errorView.backgroundColor = [UIColor whiteColor];
        _errorView.delegate = self;
    }
    [_errorView loadingError];
    [view addSubview:_errorView];
}
-(void)HideerrorView
{
    if (_errorView) {
        [_errorView removeFromSuperview];
        self.errorView=nil;
    }
}

-(void)ScreenBtnClicked
{
    [self HideNoDataView];
    [self HideerrorView];
}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    
    if (self.tapview) {
        [self.tapview removeFromSuperview];
        self.tapview = nil;
    }
}


//- (void)checkPhotoLibraryAuthorization:(void (^)(BOOL))completion {
//    PHAuthorizationStatus photoStatus = [PHPhotoLibrary authorizationStatus]; switch (photoStatus) {
//        case PHAuthorizationStatusAuthorized:
//            completion(YES);
//            break;
//        case PHAuthorizationStatusDenied:
//        {
//            [self showWithMessage:@"此功能需要您授权本App打开相册\n设置方法:打开手机设置->隐私->相册"];
//            completion(NO);
//        }
//            break;
//        case PHAuthorizationStatusNotDetermined:
//        {
//            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
//                //回到主线程
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    if (status == PHAuthorizationStatusAuthorized) {
//                        completion(YES);
//                    } else {
//                        completion(NO);
//                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"此功能需要您授权本App打开相册\n设置方法:打开手机设置->隐私->相册" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
//                        [alert show];
//                    }
//                });
//            }];
//        } break;
//        case PHAuthorizationStatusRestricted:
//            completion(NO);
//            break;
//        default:
//            completion(NO);
//            break;
//    }
//}

//- (BOOL)checkCameraAuthorization {
//    BOOL isAvailable = NO;
//    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
//    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied) {
//        // 没有权限，到设置中打开权限
//        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请在设置-->隐私-->相机，中开启本应用的相机访问权限！！" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"我知道了", nil];
//        [alert show];
//    } else {
//        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
//            [self showWithMessage:@"相机不可用"];
//        } else {
//            isAvailable = YES;
//        }
//    }
//    return isAvailable;
//}

- (void)showWithMessage:(NSString *)tipString {
    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:tipString delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alter show];
    
}

-(void)dealloc{
    if (self.title) {
        [self removeObserver:self forKeyPath:@"title"];
    }
    if (_errorView) {
        _errorView = nil;
    }
    
    if (_NoResult) {
        _NoResult = nil;
    }
    
    NSLog(@"***********baseVC基类的%@ dealloc***********",[NSString stringWithUTF8String:class_getName([self class])]);
}

@end
